package com.example.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.*;
import java.util.function.Consumer;

/*
@description:
@ClassName TaskDisposeUtils
@author chen
@create 2025-06-10 15:43
@Version 1.0
*/
public class TaskDisposeUtils
{

    public static void main(String[] args) throws InterruptedException
    {
        long startTime = System.currentTimeMillis();
        // 任务列表
        List<String> taskList = new ArrayList<>();
        for (int i = 0; i < 50; i++)
        {
            taskList.add("短信-" + i);
        }

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        // 调用工具类批处理任务
        TaskDisposeUtils.dispose(taskList, TaskDisposeUtils::disposeTask, executorService);

        System.out.println("任务处理完毕,耗时(ms):" + (System.currentTimeMillis() - startTime));
        executorService.shutdown();
    }


    public static <T> void dispose(List<T> taskList, Consumer<? super T> consumer, Executor executor) throws InterruptedException
    {
        if (taskList == null || taskList.size() == 0) return;

        Objects.nonNull(consumer);

        CountDownLatch countDownLatch = new CountDownLatch(taskList.size());
        for (T item : taskList)
        {
            executor.execute(() ->
            {
                try
                {
                    consumer.accept(item);
                }
                finally
                {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
    }


    public static void disposeTask(String task)
    {
        System.out.printf("【%s】发送成功%n", task);
    }

}
